<template>
  <div class="c-xdweug">
    <NavBar :isShowLeft="false">
      <template slot="left">
        <van-icon name="arrow-left" @click="handleBack" />
      </template>
      <template slot="content">
        <div>{{ productInfo.productName }}</div>
      </template>
    </NavBar>
    <Loading :loading="loading">
      <van-form class="c-d921q5" ref="userInfoForm">
        <div class="c-d921q5-item">
          <div class="c-d921q5-item-title">代理人</div>
          <div class="c-d921q5-item-value flex-row flex-align-center">
            <div class="c-d921q5-item-label">代理人</div>
            <van-field
              v-model="info.agent"
              name="agent"
              placeholder="请选择代理人"
              :rules="formRules.agent"
              readonly
            />
            <img
              class="c-d921q5-item-img"
              src="../img/doc3.png"
              @click="
                $refs.peoName.visible = true
                $refs.peoName.value = info.agent
              "
            />
            <PeoList
              ref="peoName"
              @confirm="value => getPartimer(value)"
              :columns="peopleList"
            />
          </div>
        </div>
        <div class="c-d921q5-item">
          <div class="c-d921q5-item-title">保单配送信息</div>
          <div class="c-d921q5-item-value flex-row flex-align-center">
            <div class="c-d921q5-item-label">收件人</div>
            <van-field
              v-model="info.receiver"
              name="receiver"
              placeholder="请选择收件人"
              :rules="formRules.receiver"
            />
          </div>
          <div class="c-d921q5-item-value flex-row flex-align-center">
            <div class="c-d921q5-item-label">手机号码</div>
            <van-field
              v-model="info.receiverMobile"
              name="receiverMobile"
              placeholder="请输入手机号码"
              :rules="formRules.receiverMobile"
            />
          </div>
          <div class="c-d921q5-item-value flex-row flex-align-center">
            <div class="c-d921q5-item-label">所在地区</div>
            <van-field
              name="reAddr"
              @click="$refs.area.visible = true"
              :rules="formRules.reAddr"
            >
              <template #input>
                <PeoArea
                  ref="area"
                  placeholder="请选择所在地区"
                  @confirm="value => handleConfirm(value, 'reAddr')"
                  :defaultValue="info.reAddr"
                  :value="info.reAddr"
                  :areaList="areaList"
                  :columnsNum="2"
                />
              </template>
            </van-field>
            <img class="c-d921q5-item-left" src="../img/left.png" />
          </div>
          <div class="c-d921q5-item-value flex-row flex-align-center">
            <div class="c-d921q5-item-label">详细地区</div>
            <van-field
              v-model="info.receiverAddress"
              name="receiverAddress"
              placeholder="请输入详细地区"
              :rules="formRules.receiverAddress"
            />
          </div>
          <div class="c-d921q5-item-value flex-row flex-align-center">
            <div class="c-d921q5-item-label">电子邮箱</div>
            <van-field
              v-model="info.receiverEmail"
              name="receiverEmail"
              placeholder="请输入电子邮箱"
              
            />
          </div>
        </div>
        <div class="c-d921q5-item">
          <div class="c-d921q5-item-title">
            资料上传
            <span class="c-d921q5-item-title-txt">
              （投保人和被保险人身份证原件正反面、投保人扣款银行卡原件正反面）
            </span>
          </div>
          <div>
            <van-uploader
              class="c-d921q5-item-upload"
              v-model="fileList"
              :multiple="true"
              :after-read="afterRead"
              :before-delete="beforeDelete"
            >
              <img src="../img/upload.png" />
            </van-uploader>
          </div>
        </div>
      </van-form>
      <!-- :class="handleColor" -->
      <div class="c-xdweug-bottom c-xdweug-bottom-active" @click="handleClick">
        提交
      </div>
    </Loading>
  </div>
</template>
<script>
import Loading from '@/components/data-loading'
import NavBar from '@/components/h5header'
import PeoList from '@/components/peoList'
import PeoArea from '@/components/popArea'
import API from '@/services/h5/product'
import comAPI from '@/services/h5/common'
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

export default {
  components: { Loading, NavBar, PeoList, PeoArea },
  data() {
    return {
      fileList: [],
      peopleList: [],
      areaList: {
        city_list: {},
        county_list: {},
        province_list: {}
      }
    }
  },
  computed: {
    ...mapGetters('common', ['formRules']),
    ...mapGetters('product', ['productInfo']),
    ...mapState('product', ['info', 'policyFiles']),
    ...mapState('loading', ['loading']),
    handleColor() {
      return this.fileList.length > 0 ? 'c-xdweug-bottom-active' : ''
    }
  },
  async created() {
    // if (this.productInfo.productName) return
    await this.getProductDetailInfo({
      contractId: this.$route.query.contractId || this.contractId
    })
    this.fileList = this.policyFiles
  },
  mounted() {
    this.init()
  },
  // watch: {
  //   peopleList(val) {
  //     if (val.length === 1) {
  //       // this.info.agent = val[0].name
  //       // this.info.partTimerId = val[0].partTimerId

  //     }
  //   }
  // },
  methods: {
    ...mapActions('product', ['getProductDetailInfo']),
    ...mapMutations('loading', ['setLoading']),
    ...mapMutations('product', [
      'setPolicyDistProp',
      'setPolicyDistObj',
      'setPolicyFiles'
    ]),
    async init() {
      let [provice, city, country] = await Promise.all([
        comAPI.getAreaList('01'),
        comAPI.getAreaList('02'),
        comAPI.getAreaList('03')
      ])
      this.areaList = {
        city_list: this.getAreaData(city),
        county_list: this.getAreaData(country),
        province_list: this.getAreaData(provice)
      }
      let customer = await API.getPartTimerList()
      if (customer.data && customer.data.code === 1000) {
        this.peopleList = []
        customer.data.data.forEach(item => {
          this.peopleList.push({
            label: item.name,
            value: item.partTimerId,
            ...item
          })
        })

        if (this.peopleList.length > 0) {
          this.setPolicyDistProp([
            'partTimerId',
            this.peopleList[0].partTimerId
          ])
          for (let i in this.peopleList[0]) {
            this.setPolicyDistProp([i, this.peopleList[0][i]])
            if (i === 'name') {
              this.setPolicyDistProp(['agent', this.peopleList[0].name])
              this.setPolicyDistProp(['receiver', this.peopleList[0].name])
            }
            if (
              i === 'receiverProvince' &&
              this.peopleList[0]['receiverProvince']
            ) {
              this.setPolicyDistProp([
                'reAddr',
                [
                  this.peopleList[0].receiverProvince,
                  this.peopleList[0].receiverCity
                ]
              ])
            }
          }
        }
      }
    },
    getAreaData(res) {
      if (res.data && res.data.code === 1000) {
        let data = res.data.data
        let obj = {}
        data.forEach(item => {
          obj[item.placeCode] = item.placeName
        })
        return obj
      }
    },
    handleBack() {
      this.$dialog
        .confirm({
          title: '此页面信息未保存，确认离开页面吗'
        })
        .then(() => {
          this.$router.go(-1)
        })
        .catch(() => {})
    },
    handleConfirm(value, prop) {
      if (prop === 'reAddr') {
        // this.info['receiverProvince'] = value[0]
        // this.info['receiverCity'] = value[1]
        // this.info['receiverCountry'] = value[2]
        this.setPolicyDistProp(['receiverProvince', value[0]])
        this.setPolicyDistProp(['receiverCity', value[1]])
        this.setPolicyDistProp(['receiverCountry', value[2]])
      }
      // this.info[prop] = value
      this.setPolicyDistProp([prop, value])
    },
    handleClick() {
      console.log('info:',this.info)
      let params = {
        contractId: this.$route.query.contractId,
        ids: [],
        partTimerId: this.info.partTimerId,
        receiver: this.info.receiver,
        receiverAddress: this.info.receiverAddress,
        receiverCity: this.info.receiverCity,
        // receiverCountry: this.info.receiverCountry,
        receiverEmail: this.info.receiverEmail,
        receiverMobile: this.info.receiverMobile,
        receiverProvince: this.info.receiverProvince
      }
      // if (
      //   this.info.agent != '' &&
      //   this.info.receiver != '' &&
      //   this.fileList.length !== 0 &&
      //   this.info.receiverAddress != '' &&
      //   this.info.receiverMobile != '' &&
      //   this.info.reAddr.length !== 0
      // ) {
      //   this.setLoading(true)
      //   API.saveReceiver(params).then(res => {
      //     if (res.data && res.data.code === 1000) {
      //       this.$router.push(`/submitSuccess/${this.$route.query.contractId}`)
      //     } else {
      //       this.$router.push(`/submitError/${this.$route.query.contractId}`)
      //     }
      //     this.setLoading(false)
      //   })
      // } else {
      //   this.$message.error('请完整填写信息')
      // }
      this.$refs.userInfoForm
        .validate()
        .then(async () => {
          if (this.info.reAddr.length !== 0 && this.fileList.length !== 0) {
            this.setLoading(true)
            let res = await API.saveReceiver(params)
            if (res.data && res.data.code === 1000) {
              this.$router.push(
                `/submitSuccess/${this.$route.query.contractId}`
              )
            } else {
              this.$router.push(`/submitError/${this.$route.query.contractId}`)
            }
          } else {
            this.$message.error('请正确完整填写信息')
          }
          this.setLoading(false)
        })
        .catch(err => {
          console.log(err)
          // this.$message.error('请正确完整填写信息')
        })
    },
    getPartimer(value) {
      // this.info.agent = value.name
      // this.info.partTimerId = value.partTimerId
      // this.setPolicyDistProp(['agent', value.name])
      // this.setPolicyDistProp(['partTimerId', value.partTimerId])
      for (let i in value) {
        this.setPolicyDistProp([i, value[i]])
        if (i === 'name') {
          this.setPolicyDistProp(['agent', value.name])
          this.setPolicyDistProp(['receiver', value.name])
        }
        if (i === 'receiverProvince' && value['receiverProvince']) {
          this.setPolicyDistProp([
            'reAddr',
            [value.receiverProvince, value.receiverCity]
          ])
        }
      }
    },
    async beforeDelete(file, detail) {
      console.log('dfsdfsdsdfsd', detail)
      return new Promise((resolve, reject) => {
        this.$dialog
          .confirm({
            title: '确认删除此张照片吗？'
          })
          .then(() => {
            if (file.id) {
              comAPI.delFile([{ id: file.id }]).then(res => {
                res.data &&
                  res.data.code === 1000 &&
                  this.$message.success('删除成功')
              })
            }
            // this.fileList.splice(detail.index, 1)
            API.getProductDetailInfo({
              contractId: this.$route.query.contractId
            }).then(detailRes => {
              const getPolicyFiles = arr => {
                if (arr.length == 0) return []
                let data = []
                arr.forEach(item => {
                  data.push({
                    url: item.filePath,
                    id: item.id
                  })
                })
                return data
              }
              this.setLoading(false)
              detailRes.data &&
                detailRes.data.code === 1000 &&
                this.setPolicyFiles(
                  getPolicyFiles(detailRes.data.data.policyFiles)
                )
            })
            resolve()
          })
          .catch(err => {
            this.$message.warning('已取消')
            reject(err)
          })
      })
    },
    afterRead(file) {
      this.setLoading(true)
      let fileData = new FormData()
      let param = {
        businessId: this.$route.query.contractId,
        attachmentType: 109,
        attachmentSubType: ''
      }
      fileData.append('param', JSON.stringify(param))
      if (!file.length) {
        fileData.append('files', file.file)
      } else {
        for (let i = 0; i < file.length; i++) {
          fileData.append('files', file[i].file)
        }
      }
      comAPI.upload(fileData).then(res => {
        if (res.data && res.data.code === 1000) {
          this.$message.success('上传成功')
          API.getProductDetailInfo({
            contractId: this.$route.query.contractId
          }).then(detailRes => {
            const getPolicyFiles = arr => {
              if (arr.length == 0) return []
              let data = []
              arr.forEach(item => {
                data.push({
                  url: item.filePath,
                  id: item.id
                })
              })
              return data
            }
            this.setLoading(false)
            res.data &&
              res.data.code === 1000 &&
              this.setPolicyFiles(
                getPolicyFiles(detailRes.data.data.policyFiles)
              )
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.c-xdweug {
  height: 100%;
  background-color: #fafafa;
  padding-bottom: 20px;
  &-bottom {
    width: 345px;
    height: 50px;
    line-height: 50px;
    border-radius: 4.5px;
    background: @c-color-primary;
    color: #fff;
    font-size: 17px;
    font-weight: bold;
    text-align: center;
    opacity: 0.5;
    margin: 0 auto;
    &-active {
      opacity: 1;
    }
  }
}
.c-d921q5 {
  height: calc(100% - 55px - 85px);
  overflow-y: scroll;
}
.c-d921q5-item {
  margin-top: 13px;
  background-color: #fff;
  padding: 15px;
  box-shadow: rgba(0, 0, 0, 0.05) 0 1px 2px 0;
  &-title {
    font-size: 19px;
    color: #000;
    font-weight: bold;
    &-txt {
      font-size: 13px;
      color: #999;
      font-weight: normal;
    }
  }
  &-img {
    width: 15px;
    height: 15px;
  }
  &-left {
    width: 7px;
    height: 13px;
  }
  &-value {
    /deep/.van-field--error .van-field__control::placeholder {
      color: #999;
    }
    // margin-top: 15px;
    border-bottom: 0.5px solid #e9e9e9;
    &:last-child {
      border: none;
    }
  }
  &-label {
    font-size: 15px;
    color: #333;
    width: 80px;
  }
  &-upload {
    margin-top: 13px;
    img {
      width: 70px;
      height: 70px;
    }
    /deep/ .van-uploader__preview-image {
      width: 70px;
      height: 70px;
    }
  }
}
</style>
